package rssgate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Text;

import rssgate.dao.PMF;
import rssgate.dao.entity.Feed;
import rssgate.dao.entity.RSSImage;
import rssgate.dao.entity.RSSItem;
import rssgate.util.LogUtils;

@SuppressWarnings("serial")
public class InstallServiceServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(InstallServiceServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		final PersistenceManager pm = PMF.get().getPersistenceManager();		
		// clear all DB
		String msg = "INFO: Start installing";
		final PrintWriter writer = resp.getWriter();
		LogUtils.logMsg(log, msg,writer);
		
		msg = "INFO: Delete all rows from " + Feed.class.getName();
		LogUtils.logMsg(log, msg,writer);
		Query newQuery = pm.newQuery("select from " + Feed.class.getName());
		Object execute = newQuery.execute();
		pm.deletePersistentAll((Collection) execute);

		msg = "INFO: Delete all rows from " + RSSImage.class.getName();
		LogUtils.logMsg(log, msg,writer);
		Query newQuery2 = pm
				.newQuery("select from " + RSSImage.class.getName());
		Object execute2 = newQuery2.execute();
		pm.deletePersistentAll((Collection) execute2);

		msg = "INFO: Delete all rows from " + RSSItem.class.getName();
		LogUtils.logMsg(log, msg,writer);		
		Query newQuery3 = pm.newQuery("select from " + RSSItem.class.getName());
		Object execute3 = newQuery3.execute();
		pm.deletePersistentAll((Collection) execute3);

		// init feeds
		msg = "INFO: Init feeds";
		LogUtils.logMsg(log, msg,writer);
		final List<String> feedUrls = ConstUtils.getFeedUrls();
		final Iterator<String> iterator = feedUrls.iterator();
		try {
			while (iterator.hasNext()) {
				final String next = iterator.next();
				final Feed fd = new Feed();
				fd.setTitle(new Text(next));
				fd.setUrl(next);
				fd.setLastUpdate(new Date(0));
				msg = "INFO: Add " + next + "feed";
				LogUtils.logMsg(log, msg,writer);
				pm.makePersistent(fd);
			}
		} finally {
			pm.close();
		}
		resp.sendRedirect("/rsslist.jsp");
	}	
}
